<template>
  <el-config-provider :locale="elLocale">
    <router-view></router-view>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import ipcMainApi from '@/ipcMainApi'

const { locale, messages } = useI18n({ useScope: 'global' })

const elLocale = computed(() => {
  const lang = locale.value || 'cn' // 确保即使locale.value为空也使用默认值
  return messages.value[lang]?.el || messages.value['cn'].el // 添加安全访问和默认值
})

const intervalLanguage = ref()

const route = useRoute()
watch(
  () => route.path,
  (newPath) => {
    const element = document.documentElement // 等价于 <html>
    if (newPath.includes('/userManagement')) {
      element.classList.add('dark')
    } else {
      element.classList.remove('dark')
    }
  },
  { immediate: true } // 立即执行一次
)


onMounted(async () => {
  // 确保初始化时设置正确的语言
  try {
    const storedLang = localStorage.getItem('lang')
    if (storedLang) {
      locale.value = storedLang
    } else {
      console.log('没有找到存储的语言设置，使用默认值:', locale.value)
    }
  } catch (error) {
    console.error('访问localStorage出错:', error)
  }

  // 获取语言
  intervalLanguage.value = setInterval(async() => {
    const language = await ipcMainApi.publicApi.getLanguage()
    localStorage.setItem('lang', language || 'cn')
    locale.value = language || 'cn'
  }, 1000)
})

onUnmounted(() => {
  clearInterval(intervalLanguage.value)
  intervalLanguage.value = null
})
</script>
